package com.dhemery.mack.actions;

import org.eclipse.jface.action.Action;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolItem;
import org.eclipse.swt.widgets.Widget;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;

import com.dhemery.mack.adapters.ImageDescriptorSource;
import com.dhemery.mack.application.MackPlugin;
import com.dhemery.mack.gui.ProjectExplorer;

public class ShowProjectExplorerAction extends Action implements IPartListener {
	private static final String name = "Project Explorer";
	public static final String ID = MackPlugin.COMMAND_ID_PREFIX + "ProjectExplorer";
	private static final String imagePath = "icons/16/tree_view.png";

	private final IWorkbenchWindow window;

	public ShowProjectExplorerAction(IWorkbenchWindow window, ImageDescriptorSource imageDescriptorSource) {
		super(name, SWT.CHECK);
		this.window = window;
		setId(ID);
		setActionDefinitionId(ID);
		setImageDescriptor(imageDescriptorSource.getImageDescriptor(imagePath));
		setChecked(false);
		window.getPartService().addPartListener(this);
	}

	private IWorkbenchPage getPage() {
		return window.getActivePage();
	}

	private void hideExplorer(IWorkbenchPage page) {
		IViewPart view = page.findView(ProjectExplorer.ID);
		page.hideView(view);
	}

	private boolean isChecked(Event event) {
		Widget widget = event.widget;
		if(widget instanceof MenuItem) return ((MenuItem)widget).getSelection();
		if(widget instanceof ToolItem) return ((ToolItem)widget).getSelection();
		if(widget instanceof Button) return ((Button)widget).getSelection();
		return false;
	}

	public void partActivated(IWorkbenchPart part) {
	}

	public void partBroughtToTop(IWorkbenchPart part) {
	}

	public void partClosed(IWorkbenchPart part) {
		if(part instanceof ProjectExplorer) setChecked(false);
	}
	
	public void partDeactivated(IWorkbenchPart part) {
	}

	public void partOpened(IWorkbenchPart part) {
		if(part instanceof ProjectExplorer) setChecked(true);
	}

	@Override
	public void runWithEvent(Event event) {
		setExplorerVisibility(isChecked(event));
	}

	private void setExplorerVisibility(boolean show) {
		IWorkbenchPage page = getPage();
		if(show) showExplorer(page);
		else hideExplorer(page);
	}

	private void showExplorer(IWorkbenchPage page) {
		try {
			page.showView(ProjectExplorer.ID);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
}
